//
//  MainViewController.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/7.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
       
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        addTheBth()
    }
    
    
    //设置子控件
    private func addChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "主页",imageName:"tabbar_home")
        addChildViewController(DiscoverTableViewController(), title: "发现",imageName:"tabbar_discover")
        
        addChildViewController(UIViewController())
        
        addChildViewController(MessageTableViewController(), title: "信息",imageName:"tabbar_message_center")
        addChildViewController(ProfileTableViewController(), title: "我",imageName:"tabbar_profile")
        
    }
    
    private func addChildViewController(vc: UIViewController,title:String?,imageName:String?) {
        
        vc.title = title;
        vc.tabBarItem.image = UIImage(named: imageName!)
        let nc = UINavigationController(rootViewController: vc)
        addChildViewController(nc)
    }
    
    //MARK: - 添加按钮
//    懒加载
    private lazy var theBth:UIButton = {
        let bth = UIButton()
        
        bth.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        bth.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        bth.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        bth.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(bth)
        
        bth.addTarget(self, action: "selectTheController", forControlEvents: UIControlEvents.TouchUpInside)
        return bth
    }()
    //设置frame
    private func addTheBth(){
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count)
        let rect = CGRectMake(0, 0, w, tabBar.bounds.height)
        theBth.frame = CGRectOffset(rect, 2 * w, 0)
        
    }
    
/// 跳转到相应控制器
    @objc func selectTheController(){
        //目标控制器
        let dv:UIViewController
        if UserAccountViewModel.sharedUserAccountViewModel.isLogin {
            dv = ComposeView()
        }else{
            dv = OAuthViewController()
        }
        
        let nv = UINavigationController(rootViewController:dv)
        presentViewController(nv, animated: true, completion: nil)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
